/*
 *          Copyright (C) 2016 jarlen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.dr.photoedit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


import com.dr.photoedit.operate.OperateConstants;
import com.dr.photoedit.operate.OperateUtils;
import com.dr.photoedit.operate.OperateView;
import com.dr.photoedit.operate.TextObject;
import com.dr.photoedit.utils.Constants;
import com.dr.photoedit.utils.ImageUtils;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 添加文字
 *
 * @author jarlen
 */
public class AddTextActivity extends Activity implements View.OnClickListener {

    private RelativeLayout content_layout;
    private OperateView operateView;
    private String camera_path;
    private String mPath = null;
    OperateUtils operateUtils;
    private ImageButton btn_ok, btn_cancel;
    private Button add, color, family, moren, faceby, facebygf;
    private LinearLayout face_linear;
    private String typeface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addtext);
        Intent intent = getIntent();
        camera_path = intent.getStringExtra("camera_path");
        operateUtils = new OperateUtils(this);
        initView();

        fillContent();

    }


    private void initView() {
        content_layout = (RelativeLayout) findViewById(R.id.mainLayout);
        face_linear = (LinearLayout) findViewById(R.id.face_linear);
        btn_ok = (ImageButton) findViewById(R.id.btn_ok);
        btn_cancel = (ImageButton) findViewById(R.id.btn_cancel);
        btn_ok.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        add = (Button) findViewById(R.id.addtext);
        color = (Button) findViewById(R.id.color);
        family = (Button) findViewById(R.id.family);

        add.setOnClickListener(this);
        color.setOnClickListener(this);
        family.setOnClickListener(this);

        moren = (Button) findViewById(R.id.moren);
        moren.setTypeface(Typeface.DEFAULT);
        faceby = (Button) findViewById(R.id.faceby);
//        faceby.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/"
//                + OperateConstants.FACE_BY + ".ttf"));
        facebygf = (Button) findViewById(R.id.facebygf);
//        facebygf.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/"
//                + OperateConstants.FACE_BYGF + ".ttf"));
        moren.setOnClickListener(this);
        faceby.setOnClickListener(this);
        facebygf.setOnClickListener(this);



    }

    private void fillContent() {
        //Bitmap resizeBmp = BitmapFactory.decodeFile(Constants.imagePath);
        //Bitmap resizeBmp = getBitmapFromUrl(Constants.imagePath,2228, 3264);
        Bitmap resizeBmp = ImageUtils.createBitmapFromPath(Constants.imagePath, this);
        //Bitmap resizeBmp = decodeBitmapTest(Constants.imagePath);
        operateView = new OperateView(AddTextActivity.this, resizeBmp);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                resizeBmp.getWidth(), resizeBmp.getHeight());

//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                ViewGroup.LayoutParams.MATCH_PARENT,   ViewGroup.LayoutParams.MATCH_PARENT);
        operateView.setLayoutParams(layoutParams);
        content_layout.addView(operateView);
        operateView.setMultiAdd(true); //设置此参数，可以添加多个文字
    }

    private void btnSave() {
        operateView.save();
        Bitmap bmp = getBitmapByView(operateView);
        if (bmp != null) {
            mPath = saveBitmap(bmp, "Test");
            Intent okData = new Intent();
            okData.putExtra("camera_path", mPath);
            setResult(RESULT_OK, okData);
            this.finish();
        }
    }

    // 将模板View的图片转化为Bitmap
    public Bitmap getBitmapByView(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    // 将生成的图片保存到内存中
    public String saveBitmap(Bitmap bitmap, String name) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File dir = new File(Constants.filePath);
            if (!dir.exists())
                dir.mkdir();
            File file = new File(Constants.filePath + name + ".jpg");
            FileOutputStream out;

            try {
                out = new FileOutputStream(file);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                    out.flush();
                    out.close();
                }
                return file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private void addfont() {
        final EditText editText = new EditText(AddTextActivity.this);
        new AlertDialog.Builder(AddTextActivity.this).setView(editText)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @SuppressLint("NewApi")
                    public void onClick(DialogInterface dialog, int which) {
                        String string = editText.getText().toString();
                        // TextObject textObj =
                        // operateUtils.getTextObject(string);
                        // if (textObj != null) {
                        // textObj.setTypeface(OperateConstants.FACE_BY);
                        // textObj.commit();
                        // }

                        if (!"".equals(string)) {
                            TextObject textObj = operateUtils.getTextObject(string,
                                    operateView, 5, 150, 100);
                            if (textObj != null) {
//                                if (menuWindow != null) {
//                                    textObj.setColor(menuWindow.getColor());
//                                }
                                textObj.setTypeface(typeface);
                                textObj.commit();
                                operateView.addItem(textObj);
                                operateView.setOnListener(new OperateView.MyListener() {
                                    public void onClick(TextObject tObject) {
                                        alert(tObject);
                                    }
                                });
                            }
                        }

                    }
                }).show();
    }

    private void alert(final TextObject tObject) {

        final EditText editText = new EditText(AddTextActivity.this);
        new AlertDialog.Builder(AddTextActivity.this).setView(editText)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @SuppressLint("NewApi")
                    public void onClick(DialogInterface dialog, int which) {
                        String string = editText.getText().toString();
                        tObject.setText(string);
                        tObject.commit();
                    }
                }).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.color:
//                menuWindow = new SelectColorPopup(AddTextActivity.this,
//                        AddTextActivity.this);
//                // 显示窗口
//                menuWindow.showAtLocation(
//                        AddTextActivity.this.findViewById(R.id.main),
//                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                break;
//            case R.id.submit:
//                menuWindow.dismiss();
//                break;
            case R.id.family:
                if (face_linear.getVisibility() == View.GONE) {
                    face_linear.setVisibility(View.VISIBLE);
                } else {
                    face_linear.setVisibility(View.GONE);
                }
                break;
            case R.id.addtext:
                addfont();
                break;
            case R.id.btn_ok:
                btnSave();
                break;
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.moren:
                typeface = null;
                face_linear.setVisibility(View.GONE);
                break;
            case R.id.faceby:
                typeface = OperateConstants.FACE_BY;
                face_linear.setVisibility(View.GONE);
                break;
            case R.id.facebygf:
                typeface = OperateConstants.FACE_BYGF;
                face_linear.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

//    private void fillContent() {
//        Bitmap resizeBmp = BitmapFactory.decodeFile(camera_path);
//        operateView = new OperateView(AddTextActivity.this, resizeBmp);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                resizeBmp.getWidth(), resizeBmp.getHeight());
//        operateView.setLayoutParams(layoutParams);
//        content_layout.addView(operateView);
//        operateView.setMultiAdd(true); //设置此参数，可以添加多个文字
//    }

    /**
     * 根据路径获取图片资源（已缩放）
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 优化
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;

        // 按照固定宽高进行缩放
        if (mWidth <= mHeight) {
            scaleWidth = (float) (width / mWidth);
            scaleHeight = (float) (height / mHeight);
        } else {
            scaleWidth = (float) (height / mWidth);
            scaleHeight = (float) (width / mHeight);
        }
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 回收
        bitmap.recycle();
        return newBitmap;
    }

    public static final float DISPLAY_WIDTH = 1270;
    public static final float DISPLAY_HEIGHT = 1080;
    /**
     * 从path中获取图片信息
     * @param path
     * @return
     */
    private Bitmap decodeBitmap(String path){

        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        Log.e("op.Width",width+"===");
        Log.e("op.Height",height+"===");
        BitmapFactory.Options op = new BitmapFactory.Options();
        //inJustDecodeBounds
        //If set to true, the decoder will return null (no bitmap), but the out…
        op.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息
        //获取比例大小
        Log.e("op.outWidth",op.outWidth+"===");
        Log.e("op.outHeight",op.outHeight+"===");
        int wRatio = (int)Math.ceil(op.outWidth/DISPLAY_WIDTH);
        int hRatio = (int)Math.ceil(op.outHeight/DISPLAY_HEIGHT);

        Log.e("op.wRatio",wRatio+"===");
        Log.e("op.hRatio",hRatio+"===");
        //如果超出指定大小，则缩小相应的比例
//        if(wRatio > 1 && hRatio > 1){
//            if(wRatio > hRatio){
//                op.inSampleSize = wRatio;
//            }else{
//                op.inSampleSize = hRatio;
//            }
//        }
        op.inSampleSize = 2;
        op.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeFile(path, op);
        Log.e("op.bmpWidth",bmp.getWidth()+"===");
        Log.e("op.bmpHeight",bmp.getHeight()+"===");
        return bmp;
    }

    private Bitmap decodeBitmapTest(String path) {
        //由于返回的图像可能太大而无法完全加载到内存中。系统有限制，需要处理。
        Display currentDisplay = getWindowManager().getDefaultDisplay();
        int defaultHeight = currentDisplay.getHeight();
        int defaultWidth = currentDisplay.getWidth();

        BitmapFactory.Options op = new BitmapFactory.Options();
        Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息
        op.inJustDecodeBounds = true;///只是为获取原始图片的尺寸，而不返回Bitmap对象
        //注上：If set to true, the decoder will return null (no bitmap), but the out... fields will still be set,
        //allowing the caller to query the bitmap without having to allocate the memory for its pixels
        try {
            //Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgFileUri), null, bitmapFactoryOptions);
            int outHeight = op.outHeight;
            int outWidth = op.outWidth;
            int heightRatio = (int) Math.ceil((float) outHeight / defaultHeight);
            int widthRatio = (int) Math.ceil((float) outWidth / defaultWidth);

            if (heightRatio > 1 || widthRatio > 1) {
                if (heightRatio > widthRatio) {
                    op.inSampleSize = heightRatio;
                } else {
                    op.inSampleSize = widthRatio;
                }
            }

            op.inSampleSize = 2;
            op.inJustDecodeBounds = false;
            bmp = BitmapFactory.decodeFile(path, op);
            return bmp;
        }catch (Exception e){

        }
        return  null;

    }
}
